"use client"

import type React from "react"

import { useState, useRef, useEffect } from "react"
import { Search, X } from "lucide-react"
import { useRouter } from "next/navigation"
import { SearchSuggestions } from "./search-suggestions"

interface SearchInputProps {
    initialQuery?: string
    onSearch?: (query: string) => void
    placeholder?: string
    className?: string
    showSuggestions?: boolean
}

export function SearchInput({
                                initialQuery = "",
                                onSearch,
                                placeholder = "搜索音乐、MV、歌单、用户",
                                className = "",
                                showSuggestions = true,
                            }: SearchInputProps) {
    const [query, setQuery] = useState(initialQuery)
    const [isFocused, setIsFocused] = useState(false)
    const [showSuggestionsBox, setShowSuggestionsBox] = useState(false)
    const inputRef = useRef<HTMLInputElement>(null)
    const containerRef = useRef<HTMLDivElement>(null)
    const router = useRouter()

    useEffect(() => {
        setQuery(initialQuery)
    }, [initialQuery])

    useEffect(() => {
        // 点击外部关闭搜索建议
        const handleClickOutside = (event: MouseEvent) => {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setShowSuggestionsBox(false)
            }
        }

        document.addEventListener("mousedown", handleClickOutside)
        return () => {
            document.removeEventListener("mousedown", handleClickOutside)
        }
    }, [])

    const handleSearch = (searchQuery: string = query) => {
        if (searchQuery.trim()) {
            // 保存到搜索历史
            const history = localStorage.getItem("searchHistory")
            let searchHistory: string[] = history ? JSON.parse(history) : []
            searchHistory = [searchQuery, ...searchHistory.filter((item) => item !== searchQuery)].slice(0, 10)
            localStorage.setItem("searchHistory", JSON.stringify(searchHistory))

            if (onSearch) {
                onSearch(searchQuery)
            } else {
                router.push(`/search?q=${encodeURIComponent(searchQuery)}`)
            }
            setShowSuggestionsBox(false)
        }
    }

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter") {
            handleSearch()
        }
    }

    const handleClear = () => {
        setQuery("")
        inputRef.current?.focus()
    }

    const handleFocus = () => {
        setIsFocused(true)
        if (showSuggestions) {
            setShowSuggestionsBox(true)
        }
    }

    return (
        <div className={`relative ${className}`} ref={containerRef}>
            <div className="relative flex items-center">
                <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <input
                        ref={inputRef}
                        type="search"
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        onKeyDown={handleKeyDown}
                        onFocus={handleFocus}
                        placeholder={placeholder}
                        className="pl-10 pr-10 py-2 w-full rounded-full border bg-background"
                    />
                    {query && (
                        <button
                            onClick={handleClear}
                            className="absolute right-3 top-1/2 transform -translate-y-1/2"
                            aria-label="清除搜索"
                        >
                            <X className="h-4 w-4 text-muted-foreground" />
                        </button>
                    )}
                </div>
                {isFocused && (
                    <button
                        onClick={() => {
                            setShowSuggestionsBox(false)
                            setIsFocused(false)
                            if (typeof window !== "undefined" && window.history.length > 1) {
                                router.back()
                            }
                        }}
                        className="ml-4 text-sm text-primary"
                    >
                        取消
                    </button>
                )}
            </div>

            {/* 搜索建议 */}
            {showSuggestionsBox && showSuggestions && (
                <SearchSuggestions
                    query={query}
                    onSelectSuggestion={handleSearch}
                    onClose={() => setShowSuggestionsBox(false)}
                />
            )}
        </div>
    )
}

